<template>
  <ECharts ref="chart" :id="id" :class="className" :style="{ height, zIndex }"></ECharts>
</template>
<script>
import { getHeroIcon } from '@/utils/dotaHelper.js'
import echarts from 'echarts'
import { h, defineComponent, ref, onMounted, defineProps } from 'vue'
import { createComponent } from 'echarts-for-vue'
import ResizeObserver from 'resize-observer-polyfill'
import { getHeroName } from '../../../../utils/dotaHelper'
export default defineComponent({
  components: {
    ECharts: createComponent({ echarts, h, ResizeObserver }),
  },
})
</script>
<script setup>
const props = defineProps({
  className: {
    type: String,
    default: 'chart',
  },
  id: {
    type: String,
    default: 'chart',
  },
  height: {
    type: String,
    default: '200px',
  },
  zIndex: {
    type: [String, Number],
    default: 1
  },
  players: {
    type: Array
  },
  type: {
    type: String,
    default: 'gold_t'
  }
})

const chart = ref(null)

onMounted(() => {
  let xAxis = []
  let series = []
  let legend = []
  props.players.forEach((item) => {
    if (xAxis.length === 0) {
      for (let i = 0; i < item.gold_t.length; i++) {
        xAxis.push(i ? `${i}:00` : 0)
      }
    }
    legend.push({
      name: item.hero_id + ''
    })
    series.push({
      name: item.hero_id + '',
      type: 'line',
      itemStyle: {
        opacity: 0
      },
      smooth: true,
      data: item[props.type]
    })
  });

  chart.value.setOption({
    title: {
      text: `玩家${props.type === 'gold_t' ? '经济' : '经验'}图`
    },
    tooltip: {
      trigger: 'axis',
      position: function (point, params, dom, rect, size) {
        return [point[0] - (point[0] < size.viewSize[0] / 2 ? 0 : size.contentSize[0]), '10%'];
      },
      formatter: function (params) {
        params.sort((a, b) => {
          return b.value - a.value
        })
        let result = ''
        params.forEach(item => {
          result += `<image  src="${getHeroIcon(item.seriesName)}" width="16" height="16" /> <span style='color:${item.color}'>${item.value}</span><br/>`
        })
        return result
      }
    },
    legend: {
      bottom: 0,
      icon: 'circle',
      formatter: function (name) {
        return getHeroName(name)
      },
      data: legend
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxis
    },
    yAxis: {
      type: 'value',
      axisTick: {
        inside: true
      },
      axisLabel: {
        inside: true,
        formatter: function (value, index) {
          return value ? Math.abs(value) / 1000 + 'k' : '';
        }
      }
    },
    series
  })
})
</script>
<style lang="scss" scoped>
.item {
  margin-top: 20px;
  span {
    font-size: 14px;
  }
}
</style>
